package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.example.entity.User;
import com.example.service.UserService;
import com.example.utils.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    UserService userService;

    /**
     * 展示登录页面
     */
    @RequestMapping("/loginPage")
    public String loginPage(){
        return "login";
    }

    /**
     * 展示注册页面
     */
    @RequestMapping("/registerPage")
    public String registerPage(){
        return "register";
    }

    /**
     * 处理登录请求
     * @param userNumber  登录账号
     * @param userPassword  登录密码
     * @return  empty查询空，success登录成功
     */
    @RequestMapping("/judgeLogin")
    @ResponseBody
    public String judgeLogin(String userNumber, String userPassword, String userType){
        User user = userService.selectByNumberAndPassword(userNumber, userPassword, userType);
        //判断是否为空
        if(user == null){
            return "empty";
        }else{
            UserContext.setCurrentUser(user);
            if(user.getUserType() == 0){
                return "user";
            }else {
                return "admin";
            }
        }
    }

    /**
     * 处理注册请求
     * @param user 封装好的user实体信息
     * @return numberRepeat账号重复，success注册成功， fail发生错误注册失败
     */
    @RequestMapping("/judgeRegister")
    @ResponseBody
    public String judgeRegister(@RequestBody User user){
        try{
            User u = userService.selectByNumber(user.getUserNumber(),user.getUserType());
            if(u != null){
               return "numberRepeat";
            }else{
                userService.save(user);
                return "success";
            }
        }catch(Exception e){
            return "fail";
        }
    }

    /**
     * 获取当前登录用户信息
     */
    @RequestMapping("/getCurrentUser")
    @ResponseBody
    public String getCurrentUser(){
        User user = (User)UserContext.getCurrentUser();
        return JSON.toJSONString(user);
    }

    /**
     * 退出登录
     */
    @RequestMapping("/logoutPage")
    public String logoutPage(){
        UserContext.setCurrentUser(null);
        return "login";
    }

}
